package uapp.facelets;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;

import javax.naming.ConfigurationException;

import uapp.Page;
import uapp.Widget;
import uapp.uAppContext;
import com.sun.facelets.tag.AbstractTagLibrary;

public class uAppTagLibrary extends AbstractTagLibrary {

	private static final String BASE_WIDGETS_PATH = "widgets/";
	private static final String NAMESPACE = "uapp/facelets";

	public uAppTagLibrary() {
		super(NAMESPACE);
		Method[] methods = getClass().getDeclaredMethods();
		for (Method m : methods) {
			if (Modifier.isStatic(m.getModifiers()))
				addFunction(m.getName(), m);
		}
	}

	public static List<Page> getLocationPages(String location) {
		location = location == null ? "" : location;
		uAppContext uapp = uAppContext.getInstance();
		List<Page> pages = new ArrayList<Page>();
		if (uapp != null) {
			for (Page page : uapp.getCurrentApplication().getPages()) {
				if (page.isVisible() && location.equals(page.getLocation()))
					pages.add(page);
			}
		}
		return pages;
	}
	
	public static List<Widget> getLocationWidgets(String location){
		location = location == null ? "" : location;
		uAppContext uapp = uAppContext.getInstance();
		List<Widget> widgets = new ArrayList<Widget>();
		if(uapp != null){
			for(Widget widget : uapp.getCurrentPage().getWidgets()){
				if(location.equals(widget.getLocation()))
					widgets.add(widget);
			}
		}
		return widgets;
	}

	public static String getWidgetPath(Widget target)
			throws ConfigurationException {
		return uAppContext.getBasePath() + BASE_WIDGETS_PATH
				+ target.getClass().getSimpleName() + "/"
				+ target.getMode() + Widget.EXTENSION;
	}
	
}
